#!/usr/bin/awk -f

######################################################################
##                                                                  ##
##  This script replaces all occurences of patterns like ##((VAR))  ##
##  with the content of the environment variable $VAR.              ##
##  Recursion is possible, e.g. ##((##((VAR))))                     ##
##                                                                  ##
##  Author: Alexander Kaplan (Alexander.Kaplan@desy.de)             ##
##                                                                  ##
######################################################################

BEGIN {
    if( ARGC<2 ) {
        print "invalid number of parameters. usage: templReplace defFile [inputfile]";
        exit 1;
    }

    dfn=ARGV[1];
    ifn=ARGV[2];

#    print "definitions file:",dfn;
#    print "input file:",ifn;
}
FILENAME == dfn && /.+\=.*/ {
   split( $0, a, "=" );
   gsub(/^[ \t]+/, "",a[1]);
   gsub(/[ \t]+$/, "",a[1]);
   gsub(/^[ \t]+/, "",a[2]);
   gsub(/[ \t]+$/, "",a[2]);
   key=a[1];
   value=a[2];
   vars[key] = value;

#   print "vars["key"]=\""vars[key]"\"";
}

FILENAME == ifn {
    line=$0;
    matches=1;
    while( matches ) {
        matches=0;

        if( match(line,"##\\(\\([^)(]*\\)\\)") != 0) {
           m=substr(line,RSTART+4,RLENGTH-6);
           line=substr(line,0,RSTART-1)ENVIRON[m]substr(line,RSTART+RLENGTH);
           matches=1;
        }

        #if( match(line,"##\\\[\\\[\[^\]\[]*\\\]\\\]") != 0) {
        if( match(line,"##\\[\\[[^\\]\\[]*\\]\\]") != 0) {
           m=substr(line,RSTART+4,RLENGTH-6);
           line=substr(line,0,RSTART-1)vars[m]substr(line,RSTART+RLENGTH);
           matches=1;
        }

        #if( match(line,"##\\\{\\\{\[^\]\[]*\\\}\\\}") != 0) {
        if( match(line,"##\\{\\{[^\\]\\[]*\\}\\}") != 0) {

           m=substr(line,RSTART+4,RLENGTH-6);
          
           filecontents=""; 
           while( (getline l <m) > 0 ) {
               filecontents=(filecontents)l"\n";
           }

           line=substr(line,0,RSTART-1)(filecontents)substr(line,RSTART+RLENGTH);
           matches=1;
        }
    }
    print line;
}
                            
